package com.web.test.servlet;

import com.web.test.bean.Grade;
import com.web.test.bean.Middle;
import com.web.test.bean.Question;
import com.web.test.dao.AnswerDao;
import com.web.test.dao.GradeDao;
import com.web.test.dao.MiddleDao;
import com.web.test.dao.QuestionDao;
import com.web.test.utils.Constants;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2017/9/23.
 */
public class MyQuestionServlet extends HttpServlet {

    QuestionDao questionDao = new QuestionDao();
    AnswerDao answerDao = new AnswerDao();
    GradeDao gradeDao = new GradeDao();
    MiddleDao middleDao = new MiddleDao();

    List<Question> errorQ = new ArrayList<Question>();


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        Map<Integer, List<Question>> questionsMap = null;
        int total = 0;
        HttpSession session = req.getSession();


        if (req.getSession().getAttribute("isLogin") != null && (Boolean) req.getSession().getAttribute("isLogin")) {
            try {
                questionsMap = questionDao.getOneQuestion();

            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (SQLException e) {
                e.printStackTrace();
            }

            if (questionsMap != null) {

                session.setAttribute("questionsMap", questionsMap);
                for (List<Question> q : questionsMap.values()) {

                    for (Question question : q) {
                        total += question.getScore();
                    }
                }

                session.setAttribute("total", total);
            }
            req.getRequestDispatcher("webexam_paper.jsp").forward(req, resp);

        } else {
            session.setAttribute("isLogin", false);
            session.setAttribute("errorMsg", "请登录后访问页面");
            resp.sendRedirect("webexam_login.jsp");
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        HttpSession session = req.getSession();
        req.setCharacterEncoding("utf-8");
        String stuNo = (String) session.getAttribute("id");
        int totalGrade = 0;

        int radioGrade = 0;
        int multiGrade = 0;
        int writeGrade = 0;

        if (session.getAttribute("questionsMap") != null) {

            Map<Integer, List<Question>> map = (Map<Integer, List<Question>>) session.getAttribute("questionsMap");

            for (Map.Entry<Integer, List<Question>> q : map.entrySet()) {

                if (q.getKey() == Constants.ONLY_SELECT_Q || q.getKey() == Constants.JUDGE_Q) {

                    for (Question question : q.getValue()) {

                        String stuOption = req.getParameter("radio" + question.getNo());

                        insertMiddle(stuNo, question.getNo(), stuOption);

                        System.out.println(stuOption+"stuOption======");

                        radioGrade += calculateG(question, stuOption);

                    }

                } else if (q.getKey() == Constants.MULTI_SELECT_Q) {

                    for (Question question : q.getValue()) {

                        String[] checkBoxS = req.getParameterValues("checkbox" + question.getNo());
                        String multiC = "";

                        for (int i = 0; i < checkBoxS.length; i++) {

                            multiC += i == checkBoxS.length - 1 ? checkBoxS[i] : checkBoxS[i] + "，";
                        }

                        insertMiddle(stuNo, question.getNo(), multiC);

                        multiGrade += calculateG(question, multiC);

                    }
                } else if (q.getKey() == Constants.WRITE_Q) {

                    for (Question question : q.getValue()) {

                        String stuOp = req.getParameter("text" + question.getNo());

                        insertMiddle(stuNo, question.getNo(), stuOp);
                        writeGrade += calculateG(question, stuOp);
                    }
                }
            }

            totalGrade = radioGrade + multiGrade + writeGrade;

//            session.setAttribute("totalGrade",totalGrade);

            System.out.println(radioGrade+"====radioGrade===");
            System.out.println(multiGrade+"=multiGrade======");
            System.out.println(writeGrade+"===writeGrade====");
            System.out.println(totalGrade+"===totalGrade====");



            try {
                gradeDao.insert(new Grade(stuNo, totalGrade));
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (SQLException e) {
                e.printStackTrace();
            }


            resp.setCharacterEncoding("utf-8");

            resp.sendRedirect("/my_grade");

        }
    }

    private int calculateG(Question question, String stuOption) {

        int grade = 0;

        try {

            if (answerDao.find(question, stuOption)) {

                grade += question.getScore();

            } else {

                errorQ.add(question);
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        System.out.println(grade+"--grade----");

        return grade;

    }

    private void insertMiddle(String stuNo, String no, String stuOption) {

        try {
            middleDao.insert(new Middle(stuNo, no, stuOption));
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}
